package com.hy;

/**
 * Created With IntelliJ IDEA.
 * Descriptions:123. 买卖股票的最佳时机 III
 * <p>
 * User:Mr.Du
 * Date:2024/7/30
 * Time:14:59
 */
public class MaxProfitII {

    public int maxProfit(int[] prices) {
        int res = 0;
        for (int i = 1; i < prices.length; i++) {
            if(prices[i] > prices[i-1]){
                res += prices[i] - prices[i-1];
            }
        }
        return res;
    }

    /**
     * dp[i][0]：第i天不持有股票的最大利润。
     * dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] + prices[i]);
     * dp[i][1]：第i天持有股票的最大利润
     * dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] - prices[i]);
     * @param prices
     * @return
     */
    public int commonMaxProfit(int[] prices) {
        int n = prices.length;
        int[][] dp = new int[n + 1][2];
        dp[0][1] = -prices[0];
        for(int i = 0;i < n;i++){
            dp[i+1][0] = Math.max(dp[i][0], dp[i][1] + prices[i]);
            dp[i+1][1] = Math.max(dp[i][1], dp[i][0] - prices[i]);
        }
        return dp[n][0];
    }
}
